#!/usr/bin/env python3
"""
Fix the TeX capacity exceeded error in the package development chapter.
The issue is LaTeX commands inside a lstlisting environment.
"""

import re
from pathlib import Path

def fix_listing_error():
    """Fix the problematic listing in package development chapter."""
    file_path = Path('./chapters/06-package-development.tex')
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Find the problematic section starting with \begin{lstlisting}[language=bash]
    # and containing LaTeX commands that should not be in a listing
    
    # Pattern to match the start of the problematic block
    start_pattern = r'\\begin\{lstlisting\}\[language=bash\]\s*\\section\{Package Development Workflow\}'
    
    match = re.search(start_pattern, content)
    if not match:
        print("Could not find the problematic listing block")
        return False
    
    # Find the corresponding \end{lstlisting} 
    start_pos = match.start()
    
    # Find the end of this particular listing
    remaining_content = content[start_pos:]
    
    # Count the nesting level to find the correct end
    listing_count = 1
    pos = len(match.group(0))
    
    while listing_count > 0 and pos < len(remaining_content):
        begin_match = re.search(r'\\begin\{lstlisting\}', remaining_content[pos:])
        end_match = re.search(r'\\end\{lstlisting\}', remaining_content[pos:])
        
        if not end_match:
            break
            
        # Check which comes first
        if begin_match and begin_match.start() < end_match.start():
            listing_count += 1
            pos += begin_match.start() + len(begin_match.group(0))
        else:
            listing_count -= 1
            if listing_count == 0:
                end_pos = start_pos + pos + end_match.start() + len(end_match.group(0))
                break
            pos += end_match.start() + len(end_match.group(0))
    
    if listing_count > 0:
        print("Could not find the matching end of listing")
        return False
    
    # Extract the content between the listing tags
    problematic_content = content[start_pos:end_pos]
    
    # Remove the listing wrapper and fix the content
    inner_content = re.sub(r'\\begin\{lstlisting\}\[language=bash\]\s*', '', problematic_content)
    inner_content = re.sub(r'\s*\\end\{lstlisting\}', '', inner_content)
    
    # Replace the problematic section
    new_content = content[:start_pos] + inner_content + content[end_pos:]
    
    # Write back the fixed content
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(new_content)
    
    print(f"Fixed the TeX capacity exceeded error in {file_path}")
    print(f"Removed problematic lstlisting wrapper around LaTeX content")
    return True

if __name__ == "__main__":
    fix_listing_error()